package cn.tedu.autoshow.passport.controller;

import cn.tedu.autoshow.commons.constants.HttpConsts;
import cn.tedu.autoshow.commons.pojo.po.LoginInfoPO;
import cn.tedu.autoshow.commons.pojo.vo.PageData;
import cn.tedu.autoshow.commons.security.LoginPrincipal;
import cn.tedu.autoshow.commons.web.JsonResult;
import cn.tedu.autoshow.passport.pojo.entity.AdminRole;
import cn.tedu.autoshow.passport.pojo.param.AdminAddNewParam;
import cn.tedu.autoshow.passport.pojo.param.AdminLoginInfoParam;
import cn.tedu.autoshow.passport.pojo.param.AdminUpdateParam;
import cn.tedu.autoshow.passport.pojo.vo.AdminListItemVO;
import cn.tedu.autoshow.passport.pojo.vo.AdminStandardVO;
import cn.tedu.autoshow.passport.service.IAdminRoleService;
import cn.tedu.autoshow.passport.service.IAdminService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("/admins")
@Api(tags = "01. 管理员管理模块")
@Slf4j
@Validated
public class AdminController {

    @Autowired
    private IAdminService service;
    @Autowired
    private IAdminRoleService adminRoleService;

    @PostMapping("/login")
    @ApiOperation("管理员登录")
    @ApiOperationSupport(order = 50)
    public JsonResult login(@Valid AdminLoginInfoParam adminLoginInfoParam,
                            @ApiIgnore HttpServletRequest request){
        String remoteAddr = request.getRemoteAddr();
        String userAgent = request.getHeader(HttpConsts.HEADER_USER_AGENT);

        String jwt = service.login(adminLoginInfoParam, remoteAddr, userAgent);
        return JsonResult.ok(jwt);
    }

    @PostMapping("/logout")
    @ApiOperation("管理员退出登录")
    @ApiOperationSupport(order = 51)
    public JsonResult logout(
            @RequestHeader(HttpConsts.HEADER_AUTHORIZATION) String jwt,
            @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal) {
        log.debug("开始处理【管理员退出登录】的请求，参数：{}", jwt);
        service.logout(jwt, loginPrincipal);
        return JsonResult.ok();
    }

    @PostMapping("/add-new")
    @ApiOperation("添加管理员")
    @ApiOperationSupport(order = 100)
    public JsonResult addNew(@Valid AdminAddNewParam adminAddNewParam){
        service.addNew(adminAddNewParam);

        return JsonResult.ok();
    }

    @PostMapping("/register")
    @ApiOperation("注册用户")
    @ApiOperationSupport(order = 100)
    public JsonResult register(@Valid AdminAddNewParam adminAddNewParam){
        adminAddNewParam.setEnable(1).setRoleIds(new Long[]{7L});
        service.addNew(adminAddNewParam);

        return JsonResult.ok();
    }


    @PostMapping("/{id:[0-9]+}/delete")
    @ApiOperation("根据ID删除用户")
    @ApiOperationSupport(order = 200)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    })
    public JsonResult deleteById(
            @Range(min = 1, message = "根据ID删除用户失败，请提交合法的ID值！")
            @PathVariable Long id){
        service.deleteById(id);
        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/update")
    //@PreAuthorize("hasAnyAuthority('/ams/admin/update')")
    @ApiOperation("根据ID更新用户")
    @ApiOperationSupport(order = 300)
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    public JsonResult updateById(
            @Range(min = 1, message = "根据ID更新用户失败，请提交合法的ID值！")
            @PathVariable Long id,
            @Valid AdminUpdateParam adminUpdateParam){
        service.updateInfoById(id, adminUpdateParam);

        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/updatePwd")
    @ApiOperation("根据ID更新用户密码")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "password", value = "用户密码", required = true, dataType = "String")
    })
    public JsonResult updatePwdById(
            @Range(min = 1, message = "根据ID更新用户失败，请提交合法的ID值！")
            @PathVariable Long id,
            @NotNull(message = "密码不能为空") String password){
        service.updatePwdById(id, password);

        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/updateAvatar")
    @ApiOperation("根据ID更新管理员头像")
    @ApiOperationSupport(order = 312)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"),
            @ApiImplicitParam(name = "avatar", value = "头像", required = true, dataType = "String")
    })
    public JsonResult updateAvatarById(
            @Range(min = 1, message = "根据ID更新用户失败，请提交合法的ID值！")
            @PathVariable Long id,
            @NotNull(message = "头像不能为空") String avatar){
        service.updateAvatarById(id, avatar);

        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/enable")
    @ApiOperation("启用管理员")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    public JsonResult setEnable(@PathVariable @Range(min = 1, message = "请提交有效的管理员ID值！") Long id) {
        service.setEnable(id);
        return JsonResult.ok();
    }

    @PostMapping("/{id:[0-9]+}/disable")
    @ApiOperation("禁用管理员")
    @ApiOperationSupport(order = 311)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "管理员ID", required = true, dataType = "long")
    })
    public JsonResult setDisable(@PathVariable @Range(min = 1, message = "请提交有效的管理员ID值！") Long id) {
        service.setDisable(id);
        return JsonResult.ok();
    }

    @PostMapping("/{adminId:[0-9]+}/insertsAdminRole")
    @ApiOperation("配置管理员角色-添加角色")
    @ApiOperationSupport(order = 310)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adminId", value = "管理员ID", required = true, dataType = "long")
    })
    public JsonResult insertsAdminRole(
            @PathVariable @Range(min = 1, message = "请提交有效的管理员ID值！") Long adminId,
                                Long[] roleIds) {
        adminRoleService.insertsAdminRoleByAdminId(adminId, roleIds);
        return JsonResult.ok();
    }

    @PostMapping("/{adminId:[0-9]+}/deletesAdminRole")
    @ApiOperation("配置管理员角色-解除角色")
    @ApiOperationSupport(order = 311)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adminId", value = "管理员ID", required = true, dataType = "long")
    })
    public JsonResult deletesAdminRole(
            @PathVariable @Range(min = 1, message = "请提交有效的管理员ID值！") Long adminId,
            Long[] roleIds) {
        adminRoleService.deletesAdminRoleByAdminId(adminId, roleIds);
        return JsonResult.ok();
    }

    @GetMapping("/{id:[0-9]+}")
    @ApiOperation("根据ID查询用户详情")
    @ApiOperationSupport(order = 410)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    })
    public JsonResult getStandardById(
            @Range(min = 1, message = "根据ID查询用户失败，请提交合法的ID值！")
            @PathVariable Long id){
        AdminStandardVO standardById = service.getStandardById(id);
        return JsonResult.ok(standardById);
    }

    @GetMapping("/index")
    @ApiOperation("根据登录信息查询用户详情")
    @ApiOperationSupport(order = 411)
    public JsonResult getStandardByJwt(
            @ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal){
        AdminStandardVO standardById = service.getStandardById(loginPrincipal.getId());
        return JsonResult.ok(standardById);
    }

    @GetMapping("/{id:[0-9]+}/roles")
    @ApiOperation("根据ID查询管理员下有多少角色")
    @ApiOperationSupport(order = 411)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long")
    })
    public JsonResult roleListByAdminId(
            @Range(min = 1, message = "根据ID查询用户失败，请提交合法的ID值！")
            @PathVariable Long id){
        List<Long> longs = adminRoleService.roleIdListByAdminId(id);
        return JsonResult.ok(longs);
    }

    @GetMapping("")
    @ApiOperation("查询管理员列表")
    @ApiOperationSupport(order = 420)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码值", paramType = "query"),
            @ApiImplicitParam(name = "queryType", value = "查询类型", example = "all")
    })
    public JsonResult list(
            @Range(min = 1, message = "查询管理员列表失败，请提供正确的页码值!") Integer pageNum,
            String queryType){
        if(pageNum == null || pageNum < 1){
            pageNum = 1;
        }
        PageData<AdminListItemVO> pageData ;
        if("all".equals(queryType)){
            pageData = service.list(pageNum, Integer.MAX_VALUE);
        }else{
            pageData = service.list(pageNum);
        }

        return JsonResult.ok(pageData);
    }

    @GetMapping("/users")
    @ApiOperation("查询管理员列表")
    @ApiOperationSupport(order = 430)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页码值", paramType = "query"),
            @ApiImplicitParam(name = "queryType", value = "查询类型", example = "all")
    })
    public JsonResult listUsers(
            @Range(min = 1, message = "查询用戶列表失败，请提供正确的页码值!") Integer pageNum,
            String queryType){
        if(pageNum == null || pageNum < 1){
            pageNum = 1;
        }
        PageData<AdminListItemVO> pageData ;
        if("all".equals(queryType)){
            pageData = service.listUsers(pageNum, Integer.MAX_VALUE);
        }else{
            pageData = service.listUsers(pageNum);
        }

        return JsonResult.ok(pageData);
    }
    //@ApiIgnore @AuthenticationPrincipal LoginPrincipal loginPrincipal

}
